package com.iwop.moto.schedule;

import com.iwop.moto.model.FPartnerStore;
import com.iwop.moto.model.SPartnetAwardInfo;
import com.iwop.moto.model.SuperRecordModel;
import com.iwop.moto.model.User;
import com.iwop.moto.service.*;
import com.iwop.moto.utils.stringUtil.BigDecimalUtil;
import com.iwop.moto.utils.stringUtil.DateUtils;
import com.iwop.moto.utils.stringUtil.StringUtils;
import com.opslab.util.DateUtil;
import org.apache.commons.collections.ListUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/** 合伙人每个月统计邀请奖励
 *
 * #author chenzq
 * #create 2017-01-17-0:38
 */
@Component
public class PartnetInviteStatisticsSchedule {

    Logger logger = Logger.getLogger(PartnetInviteStatisticsSchedule.class);

    @Autowired
    private MPromotionService promotionService;

    @Autowired
    FPartnerStoreService fPartnerStoreService;
    @Autowired
    MPaymentService mPaymentService;
    @Autowired
    StoreService storeService;
    @Autowired
    SPartnerAwardInfoService sPartnerAwardInfoService;

    /**
     * 每个月最后一天23点59分触发统计 配置文件spring.xml
     * 合伙人推广返现统计
     */
    public void schedulePartnerCashbackCensus() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String star = sdf.format(new Date());
        long startTime = System.currentTimeMillis();
        logger.info(star + " -合伙人推广返现统计 开始计算");

        //1.查询所有合伙人
        List<FPartnerStore> allPartners = fPartnerStoreService.findAll();
        Double sumMoney = 0d;
        int count = 0;
        for (FPartnerStore thisPartner : allPartners) {
            //推荐用户id集合
            List<String> childUsersByhostUser = promotionService.getChildUsersByhostUser(thisPartner.getPartnerId());
            if (childUsersByhostUser.size()==0) {
               continue;
            }
            //推荐用户是维修店集合
            List<String> storeIds = new ArrayList<>();
            //遍历所有推荐用户的维修店是否存在 存在则存入list
            for (String userSid : childUsersByhostUser) {
                SuperRecordModel srm = new SuperRecordModel();
                srm.put("user_id", userSid);
                SuperRecordModel storeByUserId = storeService.findStoreByUserId(srm);
                if (storeByUserId != null) {
                    storeIds.add(userSid);
                }
            }
            if (storeIds.size()==0)continue;
            //检测是否包含自己的维修店 如果有 基数=分销人数*2000 如果没有 基数 =（分销人数+1）*2000
            double sumPaymentMoney = 0d;
            if (storeIds.contains(thisPartner.getStoreUserId())) {
                sumPaymentMoney = storeIds.size() * 2000d;
            }else {
                sumPaymentMoney = (storeIds.size() + 1) * 2000d;
            }

            Double lastMonthAllMoney =0d;
                for (String storeId : storeIds) {
                    //统计出所有分销人数维修店上个月流水总数
                    Double thisPartnetLastInviteMoney = mPaymentService.getLastMonthBySellUserId(storeId);
                    lastMonthAllMoney = BigDecimalUtil.getAdd(lastMonthAllMoney, thisPartnetLastInviteMoney);
                }

            //判断所有分销人数维修店上个月流水总数是否大于基数 如果小于基数 则不操作任何数据
            if (sumPaymentMoney > lastMonthAllMoney) {
               continue;
            }

            //2.扣除自己 剩下的流水大于基数的50%
            Double ownWater = mPaymentService.getLastMonthBySellUserId(thisPartner.getStoreUserId());
            double fuckMoney = lastMonthAllMoney - ownWater;
            //判断如果剩下所有维修店交易流水没有大于等于基数的50% 则不做任何操作
            if ((fuckMoney < sumPaymentMoney * 0.5)) {
               continue;
            }
            //3.统计合伙人维修店的2%
            double inviteMoney = ownWater * 0.02;
            SPartnetAwardInfo awardInfo = new SPartnetAwardInfo();
            awardInfo.setReckonTime(org.apache.commons.lang3.time.DateUtils.addMonths(new Date(),-1));
            awardInfo.setPartnerName(thisPartner.getPartnerName());
            awardInfo.setPartnerRelationShopAmount(storeIds.size());
            awardInfo.setPartnerRelationShopTradeMoney(lastMonthAllMoney);
            awardInfo.setPartnerUnrelationShopTradeMoney(fuckMoney);
            awardInfo.setPartnerShopTradeMoney(ownWater);
            awardInfo.setPartnerReward(inviteMoney);
            awardInfo.setReceiveStatus(0);
            sPartnerAwardInfoService.insert(awardInfo);
            count++;
        }
        long endTime = System.currentTimeMillis();
        float seconds = (endTime - startTime) / 1000F;
        String end = sdf.format(new Date());
        logger.info("==============================================================================");
        logger.info("=                       Statistical completion                               =");
        logger.info("==============================================================================");
        logger.info(end + " -统计"+count+"个合伙人邀请奖励完成 耗时"+Float.toString(seconds)+ " seconds.");

    }

    /**
     * 每个月最后一天23点59分触发统计  配置文件spring.xml
     * 合伙人维修店推广返现统计
     */
   // @Scheduled(cron = "0 59 23 L * ?") // 每天凌晨触发一次
    public void scheduleStoreCashBackCensus(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String star = sdf.format(new Date());
        long startTime = System.currentTimeMillis();
        logger.info(star + " -合伙人维修店推广返现统计 开始计算");

        int count = 0;
        List<FPartnerStore> allPartners = fPartnerStoreService.findAll();
        for (FPartnerStore thisPartner : allPartners) {
            String thisPartnerStoreUserId = thisPartner.getStoreUserId();
            //推荐用户id集合
            List<String> partnerFromUserIds = promotionService.getChildUsersByhostUser(thisPartnerStoreUserId);
            if (partnerFromUserIds.size()==0) {
                logger.info("该合伙人店铺没有推荐用户");
                continue;
            }
            //推荐用户是维修店集合
            List<String> storeIds = new ArrayList<>();
            //遍历所有推荐用户的维修店是否存在 存在则存入list
            for (String userSid : partnerFromUserIds) {
                SuperRecordModel srm = new SuperRecordModel();
                srm.put("user_id", userSid);
                SuperRecordModel storeByUserId = storeService.findStoreByUserId(srm);
                if (storeByUserId != null) {
                    storeIds.add(userSid);
                }
            }
            if (storeIds.size()==0)continue;
            //需达标金额
            double standardMoney = (storeIds.size()) * 2000d;

            Double lastMonthAllMoney =0d;
            for (String storeId : storeIds) {
                //统计出所有分销人数维修店上个月流水总数
                Double thisPartnetLastInviteMoney = mPaymentService.getLastMonthBySellUserId(storeId);
                lastMonthAllMoney = BigDecimalUtil.getAdd(lastMonthAllMoney, thisPartnetLastInviteMoney);
            }
            //判断所有分销人数维修店上个月流水总数是否大于基数 如果小于基数 则不操作任何数据
            if (standardMoney > lastMonthAllMoney) {
                continue;
            }

            //2.扣除自己 剩下的流水大于基数的50%
            Double thisPartnerStoreTotalMoney = mPaymentService.getLastMonthBySellUserId(thisPartnerStoreUserId);
            double otherStoreTotalMoney = lastMonthAllMoney - thisPartnerStoreTotalMoney;
            //判断如果剩下所有维修店交易流水没有大于等于基数的50% 则不做任何操作
            if ((otherStoreTotalMoney < standardMoney * 0.5)) {
                continue;
            }
            double inviteMoney = thisPartnerStoreTotalMoney * 0.02;

            SPartnetAwardInfo awardInfo = new SPartnetAwardInfo();
            awardInfo.setReckonTime(org.apache.commons.lang3.time.DateUtils.addMonths(new Date(),-1));
            awardInfo.setPartnerName(thisPartner.getPartnerName());
            awardInfo.setPartnerRelationShopAmount(storeIds.size());
            awardInfo.setPartnerRelationShopTradeMoney(lastMonthAllMoney);
            awardInfo.setPartnerUnrelationShopTradeMoney(otherStoreTotalMoney);
            awardInfo.setPartnerShopTradeMoney(thisPartnerStoreTotalMoney);
            awardInfo.setPartnerReward(inviteMoney);
            awardInfo.setReceiveStatus(0);
            sPartnerAwardInfoService.insert(awardInfo);
            count++;
        }
        long endTime = System.currentTimeMillis();
        float seconds = (endTime - startTime) / 1000F;
        String end = sdf.format(new Date());
        logger.info("==============================================================================");
        logger.info("=                       Statistical completion                               =");
        logger.info("==============================================================================");
        logger.info(end + " -统计"+count+"个合伙人维修店返现结束 耗时"+Float.toString(seconds)+ " seconds.");
    }




    public Double getLastMonthBySellUserId(String seller_user_id) {

        Double lastMonthSumMoney = mPaymentService.getLastMonthBySellUserId(seller_user_id);
        return null;
    }

}
